/*
 * Created by hanzhiqiang
 * 存放公共调用的地图方法。
 */

//动态加载js方法
function DynamicLoadJs(url, callback) {
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;
    if (typeof(callback) == 'function') {
        script.onload = script.onreadystatechange = function () {
            if (!this.readyState || this.readyState === "loaded" || this.readyState === "complete") {
                callback();
                script.onload = script.onreadystatechange = null;
            }
        };
    }
    head.appendChild(script);
}

//动态加载CSS方法
function DynamicLoadCss(url) {
    var head = document.getElementsByTagName('head')[0];
    var link = document.createElement('link');
    link.type = 'text/css';
    link.rel = 'stylesheet';
    link.href = url;
    head.appendChild(link);
}

function getRootPath() {
  //获取当前网址，如： http://localhost:8088/test/test.jsp
  var curPath = window.document.location.href;
  //获取主机地址之后的目录，如： test/test.jsp
  var pathName = window.document.location.pathname;
  var pos = curPath.indexOf(pathName);
  //获取主机地址，如： http://localhost:8088
  var localhostPath = curPath.substring(0, pos);
  //获取带"/"的项目名，如：/test
  var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);
  return (localhostPath);//发布前用此
}

//根据传入几何要素和查询地址，查询其包含的几何要素
function QueryByGeometry(serivices, geometry, slayers, callback, errback) {
    require(["esri/tasks/IdentifyTask", "esri/tasks/IdentifyParameters"],
        function (IdentifyTask, IdentifyParameters) {
            var identifyTask = new IdentifyTask(serivices);
            var identifyParams = new IdentifyParameters();
            identifyParams.tolerance = 10;
            identifyParams.returnGeometry = true;
            identifyParams.layerIds = slayers;
            identifyParams.layerOption = IdentifyParameters.LAYER_OPTION_VISIBLE;
            identifyParams.width = map.width;
            identifyParams.height = map.height;
            identifyParams.mapExtent = map.extent;
            identifyParams.geometry = geometry;
            var deferred = identifyTask.execute(identifyParams);
            identifyTask.execute(identifyParams, callback, errback);
        });
}

//SQL查询方法
function QueryBySQL2(url, sql, callback, errback, geometry) {
    station_ext = [];
    require(["esri/tasks/support/Query", "esri/tasks/QueryTask", "esri/geometry/SpatialReference"],
        function (Query, QueryTask, SpatialReference) {
            var query = new Query();
            if (geometry != null) {
                query.geometry = geometry;
                query.spatialRelationship = Query.SPATIAL_REL_INTERSECTS;
            }
            var queryTask = new QueryTask(url);
            query.where = sql;
            //query.outSpatialReference = new SpatialReference({"wkid": config.wkid});
            query.outSpatialReference = map.spatialReference;
            query.returnGeometry = true;
            query.outFields = ["*"];
            //queryTask.execute(query, callback, errback);
            queryTask.execute(query).then(function(res) {
                graphicLayerPointsArray = [];
                geo = [];
                stationCount = res.features.length;
                for (var i = 0, len = res.features.length; i < len; i++) {
                    // if (graphicLayerPointsArray.indexOf(res.features[i].attributes.ObjectID) > -1) {//判断该要素是否被添加，如果添加跳出
                    //     continue;
                    // }
                    graphicLayerPointsArray.push(res.features[i].attributes.ObjectID);
                    geo = res.features[i].geometry;

                    var src = "../HRBStation/img/tdLable.png";
                    var attribute = res.features[i].attributes;

                    if (attribute.Color == "红色")
                        src = "../HRBStation/img/point_4.png";
                    else if (attribute.Color == "绿色")
                        src = "../HRBStation/img/point_3.png";
                    else if (attribute.Color == "黄色")
                        src = "../HRBStation/img/point_7.png";
                    else if (attribute.Color == "蓝色")
                        src = "../HRBStation/img/point_2.png";
                    else if (attribute.Color == "待定")
                        src = "../HRBStation/img/point_8.png";

                    var attr = [];
                    attr.x = parseFloat(geo.x);
                    attr.y = parseFloat(geo.y);
                    station_ext.push(attr);

                    var content = attribute.StationName;
                    attribute.layerID = "tdLable";

                    addPointPopo(graphicLayerPoint, geo.x, geo.y, src, 15, 15, attribute, "", "9pt", 2, 12, 2);
                    addPointPopo(graphicLayerLabel, geo.x, geo.y, "", 15, 15, attribute, content, "9pt", 2, 12, 2);
                }

                returnExtent(station_ext);
            });
        });
}
//SQL查询方法
function QueryBySQL(url, sql, callback, errback, geometry) {
    var query = new esri.tasks.Query();
    if (geometry != null) {
      query.geometry = geometry;
      query.spatialRelationship = esri.tasks.Query.SPATIAL_REL_INTERSECTS;
    }
    var queryTask = new esri.tasks.QueryTask(url);
    query.where = sql;
    query.outSpatialReference = map.spatialReference;
    query.returnGeometry = true;
    query.outFields = ["*"];
    queryTask.execute(query, callback, errback);
}

//SQL查询方法，带有排序功能
function QueryBySQLByOrderBy(url, sql, orderby, callback, errback, geometry) {
    var query = new esri.tasks.Query();
    if (geometry != null) {
        query.geometry = geometry;
        query.spatialRelationship = esri.tasks.Query.SPATIAL_REL_INTERSECTS;
    }
    var queryTask = new esri.tasks.QueryTask(url);
    query.where = sql;
    query.outSpatialReference = map.spatialReference;
    query.returnGeometry = true;
    query.orderByFields = [orderby];
    query.outFields = ["*"];
    queryTask.execute(query, callback, errback);
}

//SQL查询方法，带有排序功能
function QueryBySQLByOrderBy3(url, sql, orderby, callback, errback, geometry) {
    require(["esri/tasks/support/Query", "esri/tasks/QueryTask"],
        function (Query, QueryTask) {
            var query = new Query();
            if (geometry != null) {
                query.geometry = geometry;
                query.spatialRelationship = Query.SPATIAL_REL_INTERSECTS;
            }
            var queryTask = new QueryTask(url);
            query.where = sql;
            query.outSpatialReference = map.spatialReference;
            query.returnGeometry = true;
            query.orderByFields = [orderby];
            query.outFields = ["*"];
            queryTask.execute(query).then(callback);
        });
}



//缓冲区查询方法
function getGeometryBuffer(url, geometry, distance, buffercallback) {
    var geometryService = new esri.tasks.GeometryService(url);
    var bufferParams = new esri.tasks.BufferParameters();
    bufferParams.geometries = [geometry];
    bufferParams.distances = [distance];
    bufferParams.unit = esri.tasks.GeometryService.UNIT_METER;
    bufferParams.bufferSpatialReference = new esri.SpatialReference({"wkid": config.wkid});
    bufferParams.outSpatialReference = new esri.SpatialReference({"wkid": config.wkid});
    geometryService.buffer(bufferParams, buffercallback);
}

//查询返回失败调用函数
function queryError(res) {

}

//将当前地图可视范围转换成多边形
function ExtentToPolygon(pMap) {
    var ex = pMap.extent;
    var x1 = ex.xmin;
    var x2 = ex.xmax;
    var y1 = ex.ymin;
    var y2 = ex.ymax;
    var p1 = createPoint(x1, y1);
    var p2 = createPoint(x1, y2);
    var p3 = createPoint(x2, y2);
    var p4 = createPoint(x2, y1);
    return createPolygon([p1, p2, p3, p4, p1]);
}

//创建点
function createPoint(x, y) {
    return new esri.geometry.Point(x, y, new esri.SpatialReference({wkid: config.wkid}));
}

//创建面
function createPolygon(pointList) {
    var gon = new esri.geometry.Polygon(new esri.SpatialReference({wkid: config.wkid}));
    gon.addRing(pointList);
    return gon;
}

// 获取点样式
function getPointStyle(imgSrc, width, height) {
    var symbol = new esri.symbols.PictureMarkerSymbol(imgSrc, width, height);
    return symbol;
}

//获取面样式
function getPolygonStyle() {
    var PolygonSymbol = new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_SOLID,
        new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_DASHDOT,
            new dojo.Color([255, 0, 0, 0.55]), 2), new dojo.Color([255, 255, 0, 0.25])
    );
    return PolygonSymbol;
}

function getBufferPolygonStyle() {
    var PolygonSymbol = new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_SOLID,
        new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_DASHDOT,
            new dojo.Color([255, 0, 0, 0.55]), 2), new dojo.Color([255, 127, 127, 0.25])
    );
    return PolygonSymbol;
}


//获取线样式
function getPolylineStyle() {
    var PolylineSymbol = new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([255, 0, 0]), 2);
    return PolylineSymbol;
}

//弹出气泡框
function showInfoWindows(pMap, pt, title, content, width, height) {
    var infoWin = pMap.infoWindow;
    infoWin.setTitle(title);
    infoWin.setContent(content);
    infoWin.resize(width, height);
    infoWin.show(pMap.toScreen(pt), pMap.getInfoWindowAnchor(pt))
}

function showInfoWindows2(pMap, pt, title, content, width, height) {
  var infoWin = pMap.infoWindow;
  infoWin.setTitle(title);
  infoWin.setContent(content);
  infoWin.resize(width, height);
  infoWin.anchor = "ANCHOR_LOWERRIGHT";
  infoWin.show(pMap.toScreen(pt), pMap.getInfoWindowAnchor(pt))
}

//添加图片气泡和气泡标注文字
function addPopo2(layer, x, y, imgSrc, imgHeight, imgWidth, attributes, content, fontSize, fontOffsetX, fontOffsetY, FColor) {
    require(["esri/geometry/Point", "esri/geometry/SpatialReference",
            "esri/symbols/PictureMarkerSymbol", "esri/Graphic", "esri/symbols/TextSymbol",
            "esri/Color", "esri/symbols/Font"],
        function (Point, SpatialReference, PictureMarkerSymbol, Graphic, TextSymbol, Color, Font) {
            var pt = new Point(x, y, new SpatialReference({wkid: config.wkid}));
            if (imgSrc != "") {
                var symbol;
                symbol = new PictureMarkerSymbol({
                    "url": imgSrc,
                    "height": imgHeight,
                    "width": imgWidth,
                    "type": "esriPMS"
                });
                var graf = new Graphic(pt, symbol, attributes);
                layer.add(graf);
            }
            if (content != "") {
                var fontColor = new Color([255, 255, 255]);
                if (FColor == configColor.Black) {
                    fontColor = new Color([0, 0, 0]);
                }
                else if (FColor == configColor.White) {
                    fontColor = new Color([255, 255, 255]);
                }
                else if (FColor == configColor.Blue) {
                    fontColor = new Color([0, 0, 255]);
                }

                var textSymbol = new TextSymbol(content);
                textSymbol.color = fontColor;
                textSymbol.xoffset = fontOffsetX;
                textSymbol.yoffset = fontOffsetY;

                var font = new Font(Font.WEIGHT_BOLD);
                font.size = fontSize;
                textSymbol.font = font;
                layer.add(new Graphic(pt, textSymbol, attributes));
            }
        });
}

//添加图片气泡和气泡标注文字
function addPopo(layer, x, y, imgSrc, imgHeight, imgWidth, attributes, content, fontSize, fontOffsetX, fontOffsetY, FColor) {
    var pt = new esri.geometry.Point(x, y, new esri.SpatialReference({wkid: config.wkid}));
    if (imgSrc != "") {
        var symbol;
        symbol = new esri.symbol.PictureMarkerSymbol({
            "url": imgSrc,
            "height": imgHeight,
            "width": imgWidth,
            "type": "esriPMS"
        });
        var graf = new esri.Graphic(pt, symbol, attributes);
        layer.add(graf);
    }
    if (content != "") {
        var fontColor = new dojo.Color([255, 255, 255]);
        if (FColor == configColor.Black) {
            fontColor = new dojo.Color([0, 0, 0]);
        }
        else if (FColor == configColor.White) {
            fontColor = new dojo.Color([255, 255, 255]);
        }
        else if (FColor == configColor.Blue) {
            fontColor = new dojo.Color([0, 0, 255]);
        }
        var textSymbol = new esri.symbol.TextSymbol(content).setColor(fontColor).setOffset(fontOffsetX, fontOffsetY).setAlign(esri.symbol.TextSymbol.ALIGN_START);
        var font = new esri.symbol.Font();
        font.setSize(fontSize);
        textSymbol.setFont(font);
        layer.add(new esri.Graphic(pt, textSymbol, attributes));
    }
}

//添加饼状图
function createPie(divID, geo, title, divStyle, dt) {
    require([
        //添加自定义类型的引用
        "CustomModules_/ChartInfoWindow",
        "CustomModules_/geometryUtils",
        "dojo/_base/array",
        "dojo/dom-construct",
        "dojo/_base/window",
        "dojox/charting/Chart",
        "dojox/charting/themes/Claro",
        "dojox/charting/plot2d/Pie",
        "dojox/charting/action2d/Tooltip",
        "dojox/charting/action2d/MoveSlice",
        "dojox/charting/plot2d/Markers",
        "dojox/charting/axis2d/Default",
        "dojo/domReady!"
    ], function (ChartInfoWindow, geometryUrils,
                 array, domConstruct, win, Chart, theme, Pie, Tooltip, MoveSlice) {

        var chartData = null;
        chartData = [];
        var nodeChart = null;
        nodeChart = domConstruct.create("div", {
            id: divID,
            name: 'pie',
            style: divStyle
        }, win.body());
        var ecConfig = echarts.config;
        var myChart = echarts.init(document.getElementById(divID));

        myChart.setOption({        //加载数据图表
            title: {
                text: title,
                //subtext: '纯属虚构',
                x: 'center'
            },
            calculable: false,
            tooltip: {
                trigger: 'item',
                formatter: "{a} <br/>{b} :<br/> {c} ({d}%)"
            },
            series: [
                {
                    //name: '价格（万元/㎡）',
                    name: '套',
                    type: 'pie',
                    radius: ['50%', '70%'],
                    center: ['50%', '50%'],
                    data: dt,
                    itemStyle: {
                        emphasis: {
                            shadowBlur: 0,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        },
                        normal: {
                            label: {
                                show: true,   //显示标示文字
                                position: 'inner'
                            },
                            labelLine: {
                                show: false   //隐藏标示线
                            }
                        }
                    }
                }
            ]
        });


        var chartPoint = null;
        chartPoint = geo;
        var chartInfo = new ChartInfoWindow({
            map: map,
            chart: nodeChart,
            chartPoint: chartPoint,
            width: 10,
            height: 10
        });
    });
}

//添加柱状图
function createBar(divID, geo, title, divStyle, names, nums, lable) {
    require([
        //添加自定义类型的引用
        "CustomModules_/ChartInfoWindow",
        "CustomModules_/geometryUtils",
        "dojo/_base/array",
        "dojo/dom-construct",
        "dojo/_base/window",
        "dojox/charting/Chart",
        "dojox/charting/themes/Claro",
        "dojox/charting/plot2d/Pie",
        "dojox/charting/action2d/Tooltip",
        "dojox/charting/action2d/MoveSlice",
        "dojox/charting/plot2d/Markers",
        "dojox/charting/axis2d/Default",
        "dojo/domReady!"
    ], function (ChartInfoWindow, geometryUrils,
                 array, domConstruct, win, Chart, theme, Pie, Tooltip, MoveSlice, Markers, Default) {

        var chartData = null;
        chartData = [];
        var nodeChart = null;

        nodeChart = domConstruct.create("div", {id: divID, name: 'bar', style: divStyle}, win.body());
        var myChart = echarts.init(document.getElementById(divID));

        //柱状图
        myChart.setOption({        //加载数据图表
            title: {
                text: title,
                x: 'center',
                y: 'top',
                textAlign: 'center'
            }, grid: {
                show: 'true',
                borderWidth: '0',//去掉灰线
                x: 0,
                y: 0,//左上角距离
                x2: 0,
                y2: 0//右下角距离
            },
            tooltip: {
                show: true
            },
            xAxis: {
                type: 'category',
                axisLabel: {
                    show: false,//去除柱状图底部文字
                    rotate: 45,//倾斜度 -90 至 90 默认为0
                    textStyle: {
                        color: '#000000',
                        fontSize: '10',
                        fontWeight: 'Bold'
                    }
                },
                data: names,
                show: false
            },
            yAxis: [
                {
                    splitLine: {show: false},
                    //type : 'value'
                    data: nums,
                    show: false
                }
            ],

            series: [{
                // 根据名字对应到相应的系列
                type: 'bar',
                name: lable,

                itemStyle: {
                    normal: {
                        color: function (params) {
                            // build a color map as your need.
                            var colorList = [
                                '#C1232B', '#B5C334', '#FCCE10', '#E87C25',
                            ];
                            return colorList[params.dataIndex]
                        }
                    }
                },
                data: nums
            }]
        });

        var chartPoint = null;
        //chartPoint= geometryUrils.getPolygonCenterPoint(feature.geometry);
        chartPoint = geo;
        var chartInfo = new ChartInfoWindow({
            map: map,
            chart: nodeChart,
            chartPoint: chartPoint,
            width: 10,
            height: 10
        });
    });

}

// 添加片区多边形
function addPolygonLables(geo, content, fontOffsetX, fontOffsetY, fontSize, classifyLevel) {
    if (content != "") {
        var fontColor = new dojo.Color([0, 0, 0]);

        var fontOffsetX = fontOffsetX;
        var fontOffsetY = fontOffsetY;
        var textSymbol = new esri.symbol.TextSymbol(content).setColor(fontColor).setOffset(fontOffsetX, fontOffsetY).setAlign(esri.symbol.TextSymbol.ALIGN_START);
        var font = new esri.symbol.Font();
        font.setSize(fontSize);
        textSymbol.setFont(font, font.WEIGHT_BOLD);

        //labelPointGraphic = new esri.Graphic(geo,textSymbol);
        //map.graphics.add(labelPointGraphic);
        labelPointGraphic.add(new esri.Graphic(geo, textSymbol));
    }

}

var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
String.prototype.colorRgb = function(){
  var sColor = this.toLowerCase();
  if(sColor && reg.test(sColor)){
    if(sColor.length === 4){
      var sColorNew = "#";
      for(var i=1; i<4; i+=1){
        sColorNew += sColor.slice(i,i+1).concat(sColor.slice(i,i+1));
      }
      sColor = sColorNew;
    }
    //处理六位的颜色值
    var sColorChange = [];
    for(var i=1; i<7; i+=2){
      sColorChange.push(parseInt("0x"+sColor.slice(i,i+2)));
    }
    return "RGB(" + sColorChange.join(",") + ")";
  }else{
    return sColor;
  }
};

// 十六进制转Rgba颜色值
function hexToRgba(hex, opacity) {
  return "rgba(" + parseInt("0x" + hex.slice(1, 3)) + "," + parseInt("0x" + hex.slice(3, 5))
    + "," + parseInt("0x" + hex.slice(5, 7)) + "," + opacity + ")";
}

// 设置面图层样式
function getPolygonStyleByColor(color) {
  var PolygonSymbol = new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_SOLID,
    new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_DASHDOT,
      new esri.Color([255, 0, 0, 0.65]), 2), new esri.Color(hexToRgba(color, 0.25))
  );
  return PolygonSymbol;
}

// 设置面图层样式
function getPolygonStyleByDoubleColor(lineColor,color) {
  var PolygonSymbol = new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_SOLID,
    new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_DASHDOT,
      new esri.Color(hexToRgba(lineColor, 0.65)), 2), new esri.Color(hexToRgba(color, 0.25))
  );
  return PolygonSymbol;
}

function getPolygonStyleGray(color) {
  var lineSymbol=new SimpleLineSymbol(SimpleLineSymbol.STYLE_DASH, new Color([255, 0, 0]), 3);
  return lineSymbol;
}

$(function(){
  var mbbType=true;
  var mapbtntext=$('#mapbtntext');
  $('.mapbtnbox').on('click',function () {
    if(mbbType){
      $(this).css({
        'backgroundImage':'url("./img/sl.png")',
        'borderColor':'#fff'
      });
      mapbtntext.html('矢量图');
      mbbType=!mbbType;
      reloadMap(1);
      //切换为影像图写这
    }else{
      $(this).css({
        'backgroundImage':'url("./img/yx.jpeg")',
        'borderColor':'#000'
      });
      mapbtntext.html('影像图');
      mbbType=!mbbType;
      reloadMap(0)
      //切换为矢图写这
    }

  });
});

// 统计隶属于每个城市的小区的数目
function getCommunityPointCount(city) {
  var count = 0;
  for (var i = 0; i < objData.data.screenSelect.length; i++) {
    if (objData.data.screenSelect[i].city == city)
      count++;
  }
  return count;
}

//根据楼栋id查询楼栋空间信息
function queryLDSpatialInfo(buildId){
  var SQL = " 1=1 and BUILD_ID = "+buildId;
  QueryBySQL(config.urlIndoor+config.urlIndoor_build,SQL,(function(res){
    for(var i=0;i<res.features.length;i++) {
      var graphic = res.features[i];
      map.centerAndZoom(graphic.geometry,18);
    }
  }),(function(){console.log("查询楼栋失败...")}),null);
}

